import Message from 'tdesign-miniprogram/message/index';
import mqtt from "../../JS/mqtt.min.js";

const util = require('../../utils/util.js')


Page({
  data: {
    logs: [],
    percentage: 36,
    //实时数据
    temperature: 27.77, //温度
    humidity: 58.54, //湿度
    mq_ch0: 1000, //烟雾浓度
    mq_ch1: 1000,
    mq_ch2: 1000,
    mq_ch3: 1000,
    HBE_flag: true, //人体存在
    //阈值
    temp_th_min: 10,
    temp_th_max: 40,
    hum_th_min: 20,
    hum_th_max: 80,
    MQ_ch0_th_max: 500,
    MQ_ch1_th_max: 600,
    MQ_ch2_th_max: 700,
    MQ_ch3_th_max: 800,

    //开关量
    servos_ch0_value: false,
    servos_ch1_value: false,
    servos_ch2_value: false,
    servos_ch3_value: false,
    fan_0: false,
    fan_1: false,

    //MQTT
    client: null,
    conenctBtnText: "连接",
    host: "kd7731fa.ala.cn-hangzhou.emqxsl.cn",
    subTopic: "emqx/esp8266S",
    pubTopic: "emqx/esp8266R",
    pubMsg: "Hello! I am from WeChat miniprogram",
    receivedMsg: "",
    mqttOptions: {
      username: "DAWN_Weixin",
      password: "123123",
      reconnectPeriod: 1000, // 1000毫秒，设置为 0 禁用自动重连，两次重新连接之间的间隔时间
      connectTimeout: 30 * 1000, // 30秒，连接超时时间
    },

  },
  setValue(key, value) {
    this.setData({
      [key]: value,
    });
  },
  setHost(e) {
    this.setValue("host", e.detail.value);
  },
  setSubTopic(e) {
    this.setValue("subTopic", e.detail.value);
  },
  setPubTopic(e) {
    this.setValue("pubTopic", e.detail.value);
  },
  setPubMsg(e) {
    this.setValue("pubMsg", e.detail.value);
  },
  setRecMsg(msg) {
    this.setValue("receivedMsg", msg);
  },

  connect() {
    // MQTT-WebSocket 统一使用 /path 作为连接路径，连接时需指明，但在 EMQX Cloud 部署上使用的路径为 /mqtt
    // 因此不要忘了带上这个 /mqtt !!!
    // 微信小程序中需要将 wss 协议写为 wxs，且由于微信小程序出于安全限制，不支持 ws 协议
    try {
      const clientId = new Date().getTime();
      this.data.client = mqtt.connect(`wxs://${this.data.host}:8084/mqtt`, {
        ...this.data.mqttOptions,
        clientId,
      });

      this.data.client.on("connect", () => {
        wx.showToast({
          title: "连接成功",
        });

        this.data.client.on("message", (topic, payload) => {
          const rawData = payload.toString();
          console.log("收到消息" + rawData);
          const dataArray = rawData.split(",");

          // 解析具体字段
          const parsedData = {
            temperature: parseFloat(dataArray[0]), // 温度
            humidity: parseFloat(dataArray[1]), // 湿度
            HBE_flag: dataArray[2] === "1", // 人体存在（布尔值）
            mq_ch0: parseInt(dataArray[3], 10), // MQ1
            mq_ch1: parseInt(dataArray[4], 10), // MQ2
            mq_ch2: parseInt(dataArray[5], 10), // MQ3
            mq_ch3: parseInt(dataArray[6], 10), // MQ4
            alarm: dataArray[7] === "1" // 警报（布尔值）
          };

          // 更新界面数据
          this.setData({
            temperature: parsedData.temperature,
            humidity: parsedData.humidity,
            HBE_flag: parsedData.HBE_flag,
            mq_ch0: parsedData.mq_ch0,
            mq_ch1: parsedData.mq_ch1,
            mq_ch2: parsedData.mq_ch2,
            mq_ch3: parsedData.mq_ch3
          });
        });

        this.data.client.on("error", (error) => {
          console.log("onError", error);
        });

        this.data.client.on("reconnect", () => {
          console.log("reconnecting...");
        });

        this.data.client.on("offline", () => {
          console.log("onOffline");
        });
        // 更多 MQTT.js 相关 API 请参阅 https://github.com/mqttjs/MQTT.js#api
      });
    } catch (error) {
      console.log("mqtt.connect error", error);
    }
  },

  subscribe() {
    if (this.data.client) {
      this.data.client.subscribe(this.data.subTopic);
      // wx.showModal({
      //   content: `成功订阅主题：${this.data.subTopic}`,
      //   showCancel: false,
      // });
      return;
    }
    wx.showToast({
      title: "网络错误 请重试",
      icon: "error",
    });
  },

  unsubscribe() {
    if (this.data.client) {
      this.data.client.unsubscribe(this.data.subTopic);
      wx.showModal({
        content: `成功取消订阅主题：${this.data.subTopic}`,
        showCancel: false,
      });
      return;
    }
    wx.showToast({
      title: "请先点击连接",
      icon: "error",
    });
  },

  publish() {
    if (this.data.client) {
      this.data.client.publish(this.data.pubTopic, this.data.pubMsg);
      return;
    }
    wx.showToast({
      title: "请先点击连接",
      icon: "error",
    });
  },

  disconnect() {
    this.data.client.end();
    this.data.client = null;
    wx.showToast({
      title: "成功断开连接",
    });
  },
  showSuccessMessage(str) {
    Message.success({
      context: this,
      offset: [40, 32],
      duration: 1000,
      content: str,
    });
  },
  //控制面板
  handleChange_w1(e) {
    this.setData({
      servos_ch0_value: e.detail.value,
    });
    this.sendDeviceCommand('control');
    if (this.data.servos_ch0_value) {
      this.showSuccessMessage("窗户1打开成功");
    } else {
      this.showSuccessMessage("窗户1已关闭");
    }
  },
  handleChange_w2(e) {
    this.setData({
      servos_ch1_value: e.detail.value,
    });
    this.sendDeviceCommand('control');
    if (this.data.servos_ch1_value) {
      this.showSuccessMessage("窗户2打开成功");
    } else {
      this.showSuccessMessage("窗户2已关闭");
    }
  },
  handleChange_w3(e) {
    this.setData({
      servos_ch2_value: e.detail.value,
    });
    this.sendDeviceCommand('control');
    if (this.data.servos_ch2_value) {
      this.showSuccessMessage("窗户3打开成功");
    } else {
      this.showSuccessMessage("窗户3已关闭");
    }
  },
  handleChange_w4(e) {
    this.setData({
      servos_ch3_value: e.detail.value,
    });
    this.sendDeviceCommand('control');
    if (this.data.servos_ch3_value) {
      this.showSuccessMessage("窗户4打开成功");
    } else {
      this.showSuccessMessage("窗户4已关闭");
    }
  },
  handleChange_fan1(e) {
    this.setData({
      fan_0: e.detail.value,
    });
    this.sendDeviceCommand('control');
    if (this.data.fan_0) {
      this.showSuccessMessage("风扇1打开成功");
    } else {
      this.showSuccessMessage("风扇1已关闭");
    }
  },
  handleChange_fan2(e) {
    this.setData({
      fan_1: e.detail.value,
    });
    this.sendDeviceCommand('control');
    if (this.data.fan_1) {
      this.showSuccessMessage("风扇1打开成功");
    } else {
      this.showSuccessMessage("风扇2已关闭");
    }
  },
  //设置面板
  set_temp(e) {
    this.data.temp_th_min = e.detail.value[0];
    this.data.temp_th_max = e.detail.value[1];
  },
  set_hum(e) {
    this.data.hum_th_min = e.detail.value[0];
    this.data.hum_th_max = e.detail.value[1];
  },
  set_mq1(e) {
    this.data.MQ_ch0_th_max = e.detail.value;
  },
  set_mq2(e) {
    this.data.MQ_ch1_th_max = e.detail.value;
  },
  set_mq3(e) {
    this.data.MQ_ch2_th_max = e.detail.value;
  },
  set_mq4(e) {
    this.data.MQ_ch3_th_max = e.detail.value;
    console.log(this.data.MQ_ch3_th_max)
  },
  //重置按键
  resert_th_value() {
    this.setData({
      temp_th_min: 10,
      temp_th_max: 40,
      hum_th_min: 20,
      hum_th_max: 80,
      MQ_ch0_th_max: 500,
      MQ_ch1_th_max: 600,
      MQ_ch2_th_max: 700,
      MQ_ch3_th_max: 800,
    })
    this.showSuccessMessage("刷新成功")
  },
  //设置按键
  set_th_value() {
    this.sendDeviceCommand('threshold');
    this.showSuccessMessage("设置成功")
  },
  // 阈值数据打包函数
  packageThresholds() {
    return JSON.stringify({
      tl: this.data.temp_th_min, // 温度下限
      th: this.data.temp_th_max, // 温度上限
      hl: this.data.hum_th_min, // 湿度下限
      hh: this.data.hum_th_max, // 湿度上限
      m0: this.data.MQ_ch0_th_max, // MQ1阈值
      m1: this.data.MQ_ch1_th_max, // MQ2阈值
      m2: this.data.MQ_ch2_th_max, // MQ3阈值
      m3: this.data.MQ_ch3_th_max // MQ4阈值
    });
  },

  // 控制指令打包函数
  packageControls() {
    return JSON.stringify({
      ch0: this.data.servos_ch0_value ? 1 : 0, // 窗户1
      ch1: this.data.servos_ch1_value ? 1 : 0, // 窗户2
      ch2: this.data.servos_ch2_value ? 1 : 0, // 窗户3
      ch3: this.data.servos_ch3_value ? 1 : 0, // 窗户4
      fan1: this.data.fan_0 ? 1 : 0, // 风扇1
      fan2: this.data.fan_1 ? 1 : 0 // 风扇2
    });
  },

  // 通用发送函数
  sendDeviceCommand(type = 'threshold') {

    try {
      const payload = type === 'threshold' ?
        this.packageThresholds() :
        this.packageControls();
      console.log(payload)
      this.data.client.publish(
        'emqx/esp8266R',
        payload, {
          qos: 1
        }, // QoS 1保证至少送达一次
        (err) => {
          if (err) {
            console.error('发送失败:', err);
            wx.showToast({
              title: '指令发送失败',
              icon: 'error'
            });
          } else {
            Message.success({
              context: this,
              offset: [40, 32],
              duration: 1000,
              content: `${type === 'threshold' ? '阈值' : '控制'}指令已发送`
            });
          }
        }
      );
    } catch (e) {
      console.error('数据打包异常:', e);
      wx.showToast({
        title: '数据格式错误',
        icon: 'error'
      });
    }
  },
  onLoad() {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return {
          date: util.formatTime(new Date(log)),
          timeStamp: log
        }
      })
    })
  },
  //监听页面显示
  onShow: function () {
    //小程序切换到前台时启动MQTT连接
    this.connect();
    this.showSuccessMessage("服务器连接成功");
    this.subscribe()
  },

  //监听页面隐藏
  onHide: function () {
    //小程序切换到后台时关闭MQTT连接
    this.data.client.end()
  },
})